package com.unisound.tracelog.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.unisound.tracelog.common.config.jackson.CustomAnnotationIntrospector;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class JsonUtils {

    private static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .setSerializationInclusion(JsonInclude.Include.NON_NULL);

        AnnotationIntrospector annotationIntrospector = mapper.getSerializationConfig().getAnnotationIntrospector();
        mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(annotationIntrospector, new CustomAnnotationIntrospector()));
    }


    public static <T> T fromJson(String json, Class<T> tClass) {
        if (StringUtils.isEmpty(json)) return null;

        try {
            return mapper.readValue(json, tClass);
        } catch (Exception e) {
            return null;
        }
    }

    public static String toJson(Object o) {
        if (o == null) return null;
        if (o instanceof String) return (String) o;

        try {
            return mapper.writeValueAsString(o);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> List<T> fromJsonList(String json, Class<T> tClass) {
        if (StringUtils.isEmpty(json)) return null;

        CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
        try {
            return mapper.readValue(json, listType);
        } catch (Exception e) {
            return null;
        }
    }

}
